<?php
namespace App\Http\Controllers\Admin;

use App\Models\ChannelSource;
use App\Models\Location;
use App\Models\Member;
use App\Models\Order;
use App\Models\OrderFollow;
use App\Services\ChuangLan\ChuanglanSmsApi;
use Illuminate\Http\Request;
use Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use App\Services\Zto\ZtoApi;
use GetId3\GetId3Core as GetId3;

/**
 * 订单
 *
 * @author Miluo Huang
 */
class OrderController extends Controller
{
    /**
     * 文件存储库根路径。
     */
    protected $storage_path;

    /**
     * 文件上传字段名。
     */
    protected $filed_name = 'body';

    public function __construct()
    {
        $this->storage_path = base_path('storage/files') . DIRECTORY_SEPARATOR;
    }

    /**
     * 订单列表
     */
    public function showList(Request $request)
    {
        $data = Order::select('orders.*')->orderBy('orders.created_at', 'desc');
        if ($request->has('id')) {
            $data = $data->where('orders.id', $request->input('id'));
        }
        if ($request->has('status')) {
            $data = $data->where('orders.status', $request->input('status'));
        }
        if ($request->has('step')) {
            $data = $data->where('orders.step', $request->input('step'));
        }
        if ($request->has('start_at')) {
            $data = $data->where('orders.created_at', '>=', $request->input('start_at'));
        }
        if ($request->has('end_at')) {
            $data = $data->where('orders.created_at', '<=', $request->input('end_at'));
        }
        if ($request->has('courier_number')) {
            $data = $data->where('orders.courier_number', $request->input('courier_number'));
        }
        if ($request->has('user')) {
            $data = $data->leftJoin('members', 'members.id', '=', 'orders.member_id')->where(function ($q) use ($request) {
                $q->where('orders.real_name', 'like', '%' . $request->input('user') . '%');
                $q->orWhere('members.mobile', $request->input('user'));
                $q->orWhere('members.nickname', 'like', '%' . $request->input('user') . '%');
            });
        }
        $data = $data->paginate();
        $data->appends($request->only([
            'id',
            'status',
            'step',
            'user',
            'start_at',
            'end_at',
            'courier_number'
        ]));
        $status   = Order::$status;
        $step     = Order::$step;
        $pay_mode = Order::$pay_mode;
        //取得省市区数据
        $province = Location::where('pid', 0)->get();
        $city     = null;
        if ($request->has('province_id')) {
            $city = Location::where('pid', $request->input('province_id'))->get();
        }
        $area = null;
        if ($request->has('city_id')) {
            $area = Location::where('pid', $request->has('city_id'))->get();
        }

        return view('admin.order.list')->withData($data)->withStatus($status)->withStep($step)->withPayMode($pay_mode)->withProvince($province)->withCity($city)->withArea($area)->withGet($request->all());
    }

    /**
     * 订单编辑
     */
    public function showEdit(Request $request)
    {
        $data     = Order::find($request->input('id'));
        $status   = Order::$status;
        $step     = Order::$step;
        $pay_mode = Order::$pay_mode;
        //取得省市区数据
        $province = Location::where('pid', 0)->get();
        $city     = null;
        if (!is_null($data) && $data->province_id) {
            $city = Location::where('pid', $data->province_id)->get();
        }
        $area = null;
        if (!is_null($data) && $data->city_id) {
            $area = Location::where('pid', $data->city_id)->get();
        }
        $channel = ChannelSource::get();

        return view('admin.order.edit')->withData($data)->withStatus($status)->withStep($step)->withPayMode($pay_mode)->withProvince($province)->withCity($city)->withArea($area)->withChannel($channel);
    }

    /**
     * 订单保存
     */
    public function saveEdit(Request $request)
    {
        // 验证输入。
        $this->validate($request, [
            'status' => 'required',
            'step'   => 'required',
        ], [
            'status.required' => '请选择订单状态！',
            'step.required'   => '请选择订单步骤！',
        ]);

        // 取得要编辑的模型。
        $request->has('id') ? $data = Order::find($request->input('id')) : $data = new Order();

        //判断
        if (!$request->has('id')) {
            if (!$request->has('mobile')) {
                return redirect()->back()->withMessageError('请填写手机号。');
            }
            if (!$request->has('real_name')) {
                return redirect()->back()->withMessageError('请填写真实姓名。');
            }
            $member = Member::where('mobile', $request->input('mobile'))->first();
            if (is_null($member)) {
                $member           = new Member();
                $member->mobile   = $request->input('mobile');
                $member->nickname = $request->input('real_name');
                $member->save();
            }
            $data->member_id = $member->id;
        }
        $request->has('id') ? $step = $data->step : $step = '';

        // 编辑数据。
        $data->status = $request->input('status');
        $data->step   = $request->input('step');
        $request->has('real_name') ? $data->real_name = $request->input('real_name') : '';
        $request->has('address') ? $data->address = $request->input('address') : '';
        $request->has('province_id') ? $data->province_id = $request->input('province_id') : '';
        $request->has('city_id') ? $data->city_id = $request->input('city_id') : '';
        $request->has('area_id') ? $data->area_id = $request->input('area_id') : '';
        $data->courier_number = $request->has('courier_number') ? $request->input('courier_number') : '';
        $request->has('info') ? $data->info = $request->input('info') : '';
        $request->has('price') ? $data->price = $request->input('price') : '';
        $request->has('pay_mode') ? $data->pay_mode = $request->input('pay_mode') : '';
        $request->has('channel_id') ? $data->channel_id = $request->input('channel_id') : '';
        $request->has('leave_word') ? $data->leave_word = $request->input('leave_word') : '';
        $data->save();

        if ($step != $request->input('step') && $request->input('step') == 'DeliverGoods') {
            $member = Member::find($data->member_id);
            $info   = json_decode($data->info, true);
            if (is_array($info)) {
                $c_info = $info['数量'] . '双' . $info['颜色'] . $info['尺码'] . '码鞋子';
            } else {
                $c_info = $data->info;
            }
            $content = $data->real_name . '女士您订购的' . $c_info . '已由EMS快递寄出，快递单号为:' . $data->courier_number . ',请保持手机畅通，查收快递。如有疑问请致电：13168831555';
            $sms     = new ChuanglanSmsApi();
            $sms->sendSMS($member->mobile, $content);
        }

        // 返回成功信息。
        return redirect()->back()->withMessageSuccess('保存成功。');
    }

    /**
     * 订单客服回访
     */
    public function showServiceReturn(Request $request)
    {
        $id   = $request->input('id');
        $data = OrderFollow::where('order_id', $id)->latest('created_at')->get();

        return view('admin.order.follow_detail')->withData($data)->withGet($request->all());
    }

    /**
     * 订单客服回访保存
     */
    public function saveServiceReturn(Request $request)
    {
        $this->validate($request, [
            'id'      => [
                'required',
            ],
            'content' => [
                'required'
            ]
        ], [
            'id.required'      => '订单ID不能为空',
            'id.exists'        => '数据不存在',
            'content.required' => '回访信息不能为空',
        ]);

        $data = new OrderFollow();
        $data->admin()->associate(Auth::admin()->user());
        $data->order_id = $request->input('id');
        $data->content  = $request->input('content');
        $data->save();

        return redirect()->back()->withMessageSuccess('保存成功');
    }

    /**
     * 订单导出
     */
    public function excel(Request $request)
    {
        $data = Order::select('orders.*')->orderBy('orders.created_at', 'desc');
        if ($request->has('id')) {
            $data->where('orders.id', $request->input('id'));
        }
        if ($request->has('status')) {
            $data->where('orders.status', $request->input('status'));
        }
        if ($request->has('step')) {
            $data->where('orders.step', $request->input('step'));
        }
        if ($request->has('start_at')) {
            $data->where('orders.created_at', '>=', $request->input('start_at'));
        }
        if ($request->has('end_at')) {
            $data->where('orders.created_at', '<=', $request->input('end_at'));
        }
        if ($request->has('user')) {
            $data = $data->leftJoin('members', 'members.id', '=', 'orders.member_id')->where(function ($q) use ($request) {
                $q->where('orders.real_name', 'like', '%' . $request->input('user') . '%');
                $q->orWhere('members.mobile', $request->input('user'));
                $q->orWhere('members.nickname', 'like', '%' . $request->input('user') . '%');
            });
        }
        $data     = $data->get();
        $result   = [];
        $statu    = Order::$status;
        $step     = Order::$step;
        $pay_mode = Order::$pay_mode;
        foreach ($data as $key => $item) {
            $result[$key]['订单号'] = $item->id;
            $orders_goods        = '';
            $orders_num          = '';
            foreach ($item->goods as $row) {
//                $orders_goods .= '商品货号:' . $row->goods_number . '  ';
                $orders_num .= $row->goods_number;
            }
//            $redefinitionInfo = explode('<br>', $item->RedefinitionInfo);
//            $info_str         = '';
//            foreach ($redefinitionInfo as $k => $row) {
//                if ($k != 0) {
//                    $info_str .= '  ' . $row;
//                }
//            }
            $info                 = json_decode($item->info, true);
            $result[$key]['商品信息'] = $orders_num . ((!is_null($info) && isset($info['颜色'])) ? $info['颜色'] : '') . ((!is_null($info)&&isset($info['尺码']))  ? $info['尺码'] : '');
            $result[$key]['备注']   = str_replace('<br>', PHP_EOL, $item->Follows);
            $result[$key]['商品信息'] ? '' : $result[$key]['商品信息'] = $item->OrderGoodsInfo;
            if (!is_null($info)) {
                $result[$key]['货品名'] = isset($info['货品名']) ? $info['货品名'] : '';
                $result[$key]['尺码']  = isset($info['尺码']) ? $info['尺码'] : '';
                $result[$key]['颜色']  = isset($info['颜色']) ? $info['颜色'] : '';
                $result[$key]['数量']  = isset($info['数量']) ? $info['数量'] : '';
//                $result[$key]['型号']  = isset($info['型号']) ? $info['型号'] : '';
                if(isset($info['型号'])){
                    $orders_num = $info['型号'];
                    $result[$key]['商品信息'] = $info['型号'].','.$result[$key]['商品信息'];
                }
            } else {
                $result[$key]['货品名'] = '';
                $result[$key]['尺码']  = '';
                $result[$key]['颜色']  = '';
                $result[$key]['数量']  = '';
//                $result[$key]['型号']  = '';
            }
            $result[$key]['商品货号']  = $orders_num;
            $result[$key]['快递单号']  = $item->courier_number;
            $result[$key]['订单价格']  = $item->price;
            $result[$key]['状态']    = $statu[$item->status];
            $result[$key]['阶段']    = $step[$item->step];
            $result[$key]['用户']    = $item->real_name;
            $result[$key]['用户手机号'] = $item->member->mobile;
            $result[$key]['地址']    = preg_match('/^[0-9]*$/', $item->id) ? $item->Location . '  ' . $item->address : $item->address;
            $result[$key]['付款方式']  = isset($pay_mode[$item->pay_mode]) ? $pay_mode[$item->pay_mode] : '';
            $result[$key]['渠道']    = is_null($item->channel) ? '' : $item->channel->name;
            $result[$key]['留言'] = $item->leave_word;
            $result[$key]['下单时间']  = $item->created_at;
        }

        Excel::create('订单' . date('YmdHis'), function ($excel) use ($result) {
            $excel->sheet('Excel sheet', function ($sheet) use ($result) {
                $sheet->fromArray($result);
            });
        })->export('xls');
    }

    /**
     * 订单快递流程
     */
    public function showLogisticsTrajectory(Request $request)
    {
        $this->validate($request, [
            'id' => [
                'required',
                'exists:orders'
            ]
        ], [
            'id.required' => '订单ID不能为空',
            'id.exists'   => '数据不存在',
        ]);

        $order = Order::find($request->input('id'));
        $data  = null;
        if ($order->courier_number) {
            $courier_number = preg_replace('/\D/s', '', $order->courier_number);
            //获取物流轨迹
            $zto                  = new ZtoApi();
            $logistics_trajectory = $zto->getLogisticsTrajectory([$courier_number]);
            $data                 = json_decode($logistics_trajectory, true);
        }

        return view('admin.order.logistics_detail')->withData($data)->withGet($request->all());
    }

    /**
     * 订单快递单号导入
     */
    public function importCourierNumber(Request $request)
    {
        $this->validate($request, [
            'data' => [
                'required'
            ]
        ], [
            'data.required' => '请上传快递单号',
        ]);
        $data = $request->input('data');
        foreach ($data as $item) {
            $val = explode('|', $item);
            if (!empty($val[0])) {
                $order                 = Order::find($val[1]);
                $order->courier_number = $val[0];
                $order->save();
            }
        }

        return redirect()->back()->withMessageSuccess('保存成功。');
    }

    /**
     * 订单阶段修改
     */
    public function changeStep(Request $request)
    {
        $this->validate($request, [
            'data' => [
                'required'
            ],
            'id'   => [
                'required'
            ]
        ], [
            'data.required' => '请选择订单阶段',
            'id.required'   => '请选择订单',
        ]);

        $order       = Order::find($request->input('id'));
        $step        = $order->step;
        $order->step = $request->input('data');
        $order->save();

        if ($step != $request->input('data') && $request->input('data') == 'DeliverGoods') {
            $member = Member::find($order->member_id);
            $info   = json_decode($order->info, true);
            if (is_array($info)) {
                $c_info = $info['数量'] . '双' . $info['颜色'] . $info['尺码'] . '码鞋子';
            } else {
                $c_info = $order->info;
            }
            $content = $order->real_name . '女士您订购的' . $c_info . '已由中通快递寄出，快递单号为:' . $order->courier_number . ',请保持手机畅通，查收快递。如有疑问请致电：13168831555';
            $sms     = new ChuanglanSmsApi();
            $sms->sendSMS($member->mobile, $content);
        }

        return redirect()->back()->withMessageSuccess('保存成功。');
    }

    /**
     * 订单状态修改
     */
    public function changeSatus(Request $request)
    {
        $this->validate($request, [
            'data' => [
                'required'
            ],
            'id'   => [
                'required'
            ]
        ], [
            'data.required' => '请选择订单状态',
            'id.required'   => '请选择订单',
        ]);

        $order         = Order::find($request->input('id'));
        $order->status = $request->input('data');
        $order->save();

        return redirect()->back()->withMessageSuccess('保存成功。');
    }

    /**
     * 订单一键发货
     */
    public function aKeyDelivery(Request $request)
    {
        $datas = explode(',', $request->input('ids'));
        array_filter($datas);
        switch ($request->input('type')) {
            case 1://启用
                foreach ($datas as $item) {
                    $order = Order::find($item);
                    if (!is_null($order)) {
                        $step        = $order->step;
                        $order->step = 'DeliverGoods';
                        $order->save();
                        if ($step != $request->input('data') && $request->input('data') == 'DeliverGoods') {
                            $member = Member::find($order->member_id);
                            $info   = json_decode($order->info, true);
                            if (is_array($info)) {
                                $c_info = $info['数量'] . '双' . $info['颜色'] . $info['尺码'] . '码鞋子';
                            } else {
                                $c_info = $order->info;
                            }
                            $content = $order->real_name . '女士您订购的' . $c_info . '已由中通快递寄出，快递单号为:' . $order->courier_number . ',请保持手机畅通，查收快递。如有疑问请致电：13168831555';
                            $sms     = new ChuanglanSmsApi();
                            $sms->sendSMS($member->mobile, $content);
                        }
                    }
                }
                break;
            default;
        }

        return redirect()->back()->withMessageSuccess('保存成功。');
    }

    /**
     * 待发货订单列表
     *
     * @param Request $request
     *
     * @return mixed
     */
    public function showDropShippingList(Request $request)
    {
        $data = Order::select('orders.*')->orderBy('orders.created_at', 'desc')->where('orders.step', 'WaitDeliverGoods');
        if ($request->has('id')) {
            $data = $data->where('orders.id', $request->input('id'));
        }
//        if ($request->has('status')) {
//            $data = $data->where('orders.status', $request->input('status'));
//        }
//        if ($request->has('step')) {
//            $data = $data->where('orders.step', $request->input('step'));
//        }
        if ($request->has('start_at')) {
            $data = $data->where('orders.created_at', '>=', $request->input('start_at'));
        }
        if ($request->has('end_at')) {
            $data = $data->where('orders.created_at', '<=', $request->input('end_at'));
        }
        if ($request->has('courier_number')) {
            $data = $data->where('orders.courier_number', $request->input('courier_number'));
        }
        if ($request->has('user')) {
            $data = $data->leftJoin('members', 'members.id', '=', 'orders.member_id')->where(function ($q) use ($request) {
                $q->where('orders.real_name', 'like', '%' . $request->input('user') . '%');
                $q->orWhere('members.mobile', $request->input('user'));
                $q->orWhere('members.nickname', 'like', '%' . $request->input('user') . '%');
            });
        }
        $data = $data->paginate();
        $data->appends($request->only([
            'id',
            'status',
            'step',
            'user',
            'start_at',
            'end_at',
            'courier_number'
        ]));
        $status   = Order::$status;
        $step     = Order::$step;
        $pay_mode = Order::$pay_mode;
        //取得省市区数据
        $province = Location::where('pid', 0)->get();
        $city     = null;
        if ($request->has('province_id')) {
            $city = Location::where('pid', $request->input('province_id'))->get();
        }
        $area = null;
        if ($request->has('city_id')) {
            $area = Location::where('pid', $request->has('city_id'))->get();
        }

        return view('admin.order.drop_shipping_list')->withData($data)->withStatus($status)->withStep($step)->withPayMode($pay_mode)->withProvince($province)->withCity($city)->withArea($area)->withGet($request->all());
    }

    /**
     * 已发货订单列表
     *
     * @param Request $request
     *
     * @return mixed
     */
    public function showHasBeenShippedList(Request $request)
    {
        $data = Order::select('orders.*')->orderBy('orders.created_at', 'desc')->where('orders.step', 'DeliverGoods');
        if ($request->has('id')) {
            $data = $data->where('orders.id', $request->input('id'));
        }
//        if ($request->has('status')) {
//            $data = $data->where('orders.status', $request->input('status'));
//        }
//        if ($request->has('step')) {
//            $data = $data->where('orders.step', $request->input('step'));
//        }
        if ($request->has('start_at')) {
            $data = $data->where('orders.created_at', '>=', $request->input('start_at'));
        }
        if ($request->has('end_at')) {
            $data = $data->where('orders.created_at', '<=', $request->input('end_at'));
        }
        if ($request->has('courier_number')) {
            $data = $data->where('orders.courier_number', $request->input('courier_number'));
        }
        if ($request->has('user')) {
            $data = $data->leftJoin('members', 'members.id', '=', 'orders.member_id')->where(function ($q) use ($request) {
                $q->where('orders.real_name', 'like', '%' . $request->input('user') . '%');
                $q->orWhere('members.mobile', $request->input('user'));
                $q->orWhere('members.nickname', 'like', '%' . $request->input('user') . '%');
            });
        }
        $data = $data->paginate();
        $data->appends($request->only([
            'id',
            'status',
            'step',
            'user',
            'start_at',
            'end_at',
            'courier_number'
        ]));
        $status   = Order::$status;
        $step     = Order::$step;
        $pay_mode = Order::$pay_mode;
        //取得省市区数据
        $province = Location::where('pid', 0)->get();
        $city     = null;
        if ($request->has('province_id')) {
            $city = Location::where('pid', $request->input('province_id'))->get();
        }
        $area = null;
        if ($request->has('city_id')) {
            $area = Location::where('pid', $request->has('city_id'))->get();
        }

        return view('admin.order.has_been_shipped_list')->withData($data)->withStatus($status)->withStep($step)->withPayMode($pay_mode)->withProvince($province)->withCity($city)->withArea($area)->withGet($request->all());
    }

    /**
     * 取消订单列表
     *
     * @param Request $request
     *
     * @return mixed
     */
    public function showCancelList(Request $request)
    {
        $data = Order::select('orders.*')->orderBy('orders.created_at', 'desc')->where('orders.status', 'Canceled')->where('orders.step', 'Completed');
        if ($request->has('id')) {
            $data = $data->where('orders.id', $request->input('id'));
        }
//        if ($request->has('status')) {
//            $data = $data->where('orders.status', $request->input('status'));
//        }
//        if ($request->has('step')) {
//            $data = $data->where('orders.step', $request->input('step'));
//        }
        if ($request->has('start_at')) {
            $data = $data->where('orders.created_at', '>=', $request->input('start_at'));
        }
        if ($request->has('end_at')) {
            $data = $data->where('orders.created_at', '<=', $request->input('end_at'));
        }
        if ($request->has('courier_number')) {
            $data = $data->where('orders.courier_number', $request->input('courier_number'));
        }
        if ($request->has('user')) {
            $data = $data->leftJoin('members', 'members.id', '=', 'orders.member_id')->where(function ($q) use ($request) {
                $q->where('orders.real_name', 'like', '%' . $request->input('user') . '%');
                $q->orWhere('members.mobile', $request->input('user'));
                $q->orWhere('members.nickname', 'like', '%' . $request->input('user') . '%');
            });
        }
        $data = $data->paginate();
        $data->appends($request->only([
            'id',
            'status',
            'step',
            'user',
            'start_at',
            'end_at',
            'courier_number'
        ]));
        $status   = Order::$status;
        $step     = Order::$step;
        $pay_mode = Order::$pay_mode;
        //取得省市区数据
        $province = Location::where('pid', 0)->get();
        $city     = null;
        if ($request->has('province_id')) {
            $city = Location::where('pid', $request->input('province_id'))->get();
        }
        $area = null;
        if ($request->has('city_id')) {
            $area = Location::where('pid', $request->has('city_id'))->get();
        }

        return view('admin.order.cancel_list')->withData($data)->withStatus($status)->withStep($step)->withPayMode($pay_mode)->withProvince($province)->withCity($city)->withArea($area)->withGet($request->all());
    }

    /**
     * 完成订单列表
     *
     * @param Request $request
     *
     * @return mixed
     */
    public function showCompleteList(Request $request)
    {
        $data = Order::select('orders.*')->orderBy('orders.created_at', 'desc')->where(function ($q) {
            $q->where('orders.status', 'Completed');
            $q->Where('orders.step', 'Completed');
        });
        if ($request->has('id')) {
            $data = $data->where('orders.id', $request->input('id'));
        }
//        if ($request->has('status')) {
//            $data = $data->where('orders.status', $request->input('status'));
//        }
//        if ($request->has('step')) {
//            $data = $data->where('orders.step', $request->input('step'));
//        }
        if ($request->has('start_at')) {
            $data = $data->where('orders.created_at', '>=', $request->input('start_at'));
        }
        if ($request->has('end_at')) {
            $data = $data->where('orders.created_at', '<=', $request->input('end_at'));
        }
        if ($request->has('courier_number')) {
            $data = $data->where('orders.courier_number', $request->input('courier_number'));
        }
        if ($request->has('user')) {
            $data = $data->leftJoin('members', 'members.id', '=', 'orders.member_id')->where(function ($q) use ($request) {
                $q->where('orders.real_name', 'like', '%' . $request->input('user') . '%');
                $q->orWhere('members.mobile', $request->input('user'));
                $q->orWhere('members.nickname', 'like', '%' . $request->input('user') . '%');
            });
        }
        $data = $data->paginate();
        $data->appends($request->only([
            'id',
            'status',
            'step',
            'user',
            'start_at',
            'end_at',
            'courier_number'
        ]));
        $status   = Order::$status;
        $step     = Order::$step;
        $pay_mode = Order::$pay_mode;
        //取得省市区数据
        $province = Location::where('pid', 0)->get();
        $city     = null;
        if ($request->has('province_id')) {
            $city = Location::where('pid', $request->input('province_id'))->get();
        }
        $area = null;
        if ($request->has('city_id')) {
            $area = Location::where('pid', $request->has('city_id'))->get();
        }

        return view('admin.order.complete_list')->withData($data)->withStatus($status)->withStep($step)->withPayMode($pay_mode)->withProvince($province)->withCity($city)->withArea($area)->withGet($request->all());
    }

    /**
     * 拒签订单列表
     *
     * @param Request $request
     *
     * @return mixed
     */
    public function showRefusalList(Request $request)
    {
        $data = Order::select('orders.*')->orderBy('orders.created_at', 'desc')->where('orders.status', 'Deny')->where('orders.step', 'Completed');
        if ($request->has('id')) {
            $data = $data->where('orders.id', $request->input('id'));
        }
//        if ($request->has('status')) {
//            $data = $data->where('orders.status', $request->input('status'));
//        }
//        if ($request->has('step')) {
//            $data = $data->where('orders.step', $request->input('step'));
//        }
        if ($request->has('start_at')) {
            $data = $data->where('orders.created_at', '>=', $request->input('start_at'));
        }
        if ($request->has('end_at')) {
            $data = $data->where('orders.created_at', '<=', $request->input('end_at'));
        }
        if ($request->has('courier_number')) {
            $data = $data->where('orders.courier_number', $request->input('courier_number'));
        }
        if ($request->has('user')) {
            $data = $data->leftJoin('members', 'members.id', '=', 'orders.member_id')->where(function ($q) use ($request) {
                $q->where('orders.real_name', 'like', '%' . $request->input('user') . '%');
                $q->orWhere('members.mobile', $request->input('user'));
                $q->orWhere('members.nickname', 'like', '%' . $request->input('user') . '%');
            });
        }
        $data = $data->paginate();
        $data->appends($request->only([
            'id',
            'status',
            'step',
            'user',
            'start_at',
            'end_at',
            'courier_number'
        ]));
        $status   = Order::$status;
        $step     = Order::$step;
        $pay_mode = Order::$pay_mode;
        //取得省市区数据
        $province = Location::where('pid', 0)->get();
        $city     = null;
        if ($request->has('province_id')) {
            $city = Location::where('pid', $request->input('province_id'))->get();
        }
        $area = null;
        if ($request->has('city_id')) {
            $area = Location::where('pid', $request->has('city_id'))->get();
        }

        return view('admin.order.refusal_list')->withData($data)->withStatus($status)->withStep($step)->withPayMode($pay_mode)->withProvince($province)->withCity($city)->withArea($area)->withGet($request->all());
    }

    /**
     * 售后订单列表
     *
     * @param Request $request
     *
     * @return mixed
     */
    public function showAfterSalesList(Request $request)
    {
        $data = Order::select('orders.*')->orderBy('orders.created_at', 'desc')->where(function ($q) {
            $q->where(function ($k) {
                $k->where('orders.step', 'Exchange');
                $k->where('orders.status', 'ToBePrinted');
            });
            $q->orWhere(function ($k) {
                $k->where('orders.step', 'Return');
                $k->where('orders.status', 'Deny');
            });
        });
        if ($request->has('id')) {
            $data = $data->where('orders.id', $request->input('id'));
        }
//        if ($request->has('status')) {
//            $data = $data->where('orders.status', $request->input('status'));
//        }
//        if ($request->has('step')) {
//            $data = $data->where('orders.step', $request->input('step'));
//        }
        if ($request->has('start_at')) {
            $data = $data->where('orders.created_at', '>=', $request->input('start_at'));
        }
        if ($request->has('end_at')) {
            $data = $data->where('orders.created_at', '<=', $request->input('end_at'));
        }
        if ($request->has('courier_number')) {
            $data = $data->where('orders.courier_number', $request->input('courier_number'));
        }
        if ($request->has('user')) {
            $data = $data->leftJoin('members', 'members.id', '=', 'orders.member_id')->where(function ($q) use ($request) {
                $q->where('orders.real_name', 'like', '%' . $request->input('user') . '%');
                $q->orWhere('members.mobile', $request->input('user'));
                $q->orWhere('members.nickname', 'like', '%' . $request->input('user') . '%');
            });
        }
        $data = $data->paginate();
        $data->appends($request->only([
            'id',
            'status',
            'step',
            'user',
            'start_at',
            'end_at',
            'courier_number'
        ]));
        $status   = Order::$status;
        $step     = Order::$step;
        $pay_mode = Order::$pay_mode;
        //取得省市区数据
        $province = Location::where('pid', 0)->get();
        $city     = null;
        if ($request->has('province_id')) {
            $city = Location::where('pid', $request->input('province_id'))->get();
        }
        $area = null;
        if ($request->has('city_id')) {
            $area = Location::where('pid', $request->has('city_id'))->get();
        }

        return view('admin.order.after_sale_list')->withData($data)->withStatus($status)->withStep($step)->withPayMode($pay_mode)->withProvince($province)->withCity($city)->withArea($area)->withGet($request->all());
    }

    public function getImportExcelFile(Request $request){
        return view('admin.order.import');
    }

    public function importExcelFile(Request $request){
        $this->validate($request, [
            'file_hash' => [
                'required'
            ],
            'type'   => [
                'required'
            ]
        ], [
            'file_hash.required' => '请选择excel',
            'type.required'   => '请选择类型',
        ]);
        $storage = \App\Models\Storage::where('hash',$request->input('file_hash'))->first();
        $path = $this->storage_path.$storage->path;
        $res = [];
        Excel::load($path,function($reader) use( &$res ) {
            $reader = $reader->getSheet(0);
            $res = $reader->toArray();
        });
        $type = $request->input('type');
        $order_no_word = '不存在:';
        $courier_no_word = '不存在:';
        $qian=array(" ","　","\t","\n","\r");
        $hou=array("","","","","");
        foreach($res as $key=>$item){
            $item = str_replace($qian,$hou,$item);
            if(count($item)>1) {
                $order_id   = isset($item[0]) ? $item[0] : 0;
                $courier_no = isset($item[1]) ? $item[1] : 0;
            }else{
                $order_id   = isset($item[0]) ? $item[0] : 0;
                $courier_no = isset($item[0]) ? $item[0] : 0;
            }
            $order = Order::find($order_id);
            $order_by_courier_no = Order::where('courier_number',$courier_no)->first();
                switch ($type) {
                    case 1:
                        if(!is_null($order)) {
                            $order->status = 'Normal';
                            $order->step   = 'DeliverGoods';
                        }elseif(!is_null($order_by_courier_no)){
                            $order_by_courier_no->status = 'Normal';
                            $order_by_courier_no->step   = 'DeliverGoods';
                        }
                        break;
                    case 2:
                        if(!is_null($order)) {
                            $order->status = 'Completed';
                            $order->step   = 'Completed';
                        }elseif(!is_null($order_by_courier_no)){
                            $order_by_courier_no->status = 'Completed';
                            $order_by_courier_no->step   = 'Completed';
                        }
                        break;
                    case 3:
                        if(!is_null($order)) {
                            $order->status = 'Deny';
                            $order->step   = 'Completed';
                        }elseif(!is_null($order_by_courier_no)){
                            $order_by_courier_no->status = 'Deny';
                            $order_by_courier_no->step   = 'Completed';
                        }
                        break;
                }
                if(!is_null($order)) {
                    $order->courier_number = $courier_no;
                    $order->save();
                }elseif(!is_null($order_by_courier_no)){
                    $order_by_courier_no->courier_number = $courier_no;
                    $order_by_courier_no->save();
                }else{
                    if(($order_id)){
                        $order_no_word .= $order_id."<br>";
                    }else{
                        $courier_no_word .= $courier_no.'<br>';
                    }
                }
            }
//        }

        return redirect()->back()->withMessageSuccess('保存成功。<br>'.$order_no_word.'<br>'.$courier_no_word);
    }

    public function getImportGeneralizeOrder(Request $request){
        return view('admin.order.import-generalize');
    }

    public function importGeneralizeOrder(Request $request){
        $storage = \App\Models\Storage::where('hash',$request->input('file_hash'))->first();
        $path = $this->storage_path.$storage->path;
        $res = [];
        Excel::load($path,function($reader) use( &$res ) {
            $reader = $reader->getSheet(0);
            $res = $reader->toArray();
        });//dd($res);
        $count = count($res);
        DB::beginTransaction();
        foreach ($res as $key=>$item){
            if($key == 0){
                continue;
            }
            if(!$item[0] && $count == $key+1){
                break;
            }
            if(!$item[0]){
                continue;
            }
            $mobile = substr($item[7],0,11);//dd($item[6]);
            $member = Member::where('mobile', $mobile)->first();
            if (is_null($member)) {
                $member           = new Member();
                $member->mobile   = $mobile;
                $member->nickname = $item[6] ? $item[6] : '';
                $member->save();
            }

            $province_id = Location::select('id','name')->where('name','like','%'.$item[8].'%')->first();
            $city_id = Location::select('id')->where('name','like','%'.$item[9].'%')->first();
            $area_id = Location::select('id')->where('name','like','%'.$item[10].'%')->first();

            $order = new Order();
            $order->id = $item[0];
            $size = substr($item[2],-2);
            preg_match_all("/:(.*),/i",$item[2],$color);
            $color = (isset($color[1]) && isset($color[1][0])) ? ($color[1][0]) : '';
            $order->info = json_encode([
                '货品名'=>mb_check_encoding($item[2], 'UTF-8') ? $item[2] : mb_convert_encoding($item[2], 'UTF-8', 'gbk') ,
                '数量'=>mb_check_encoding($item[3], 'UTF-8') ? $item[3] : mb_convert_encoding($item[3], 'UTF-8', 'gbk'),
                '尺码'=>mb_check_encoding($size, 'UTF-8') ? $size : mb_convert_encoding($size, 'UTF-8', 'gbk'),
                '颜色'=>mb_check_encoding($color, 'UTF-8') ? $color : mb_convert_encoding($color, 'UTF-8', 'gbk'),
                '型号'=>mb_check_encoding($item[1], 'UTF-8') ? $item[1] : mb_convert_encoding($item[1], 'UTF-8', 'gbk')
            ]);
            $order->price = $item[5];
            $order->real_name = $item[6] ? $item[6] : '';
            $order->member_id = $member->id;
            $order->address = is_null($province_id) ? $item[11] : $province_id->name.$item[11];
            $order->province_id = is_null($province_id) ? 0 : $province_id->id;
            $order->city_id = is_null($city_id) ? 0 : $city_id->id;
            $order->area_id = is_null($area_id) ? 0 : $area_id->id;
            $order->save();
        }
        DB::commit();

        return redirect()->back()->withMessageSuccess('操作成功。');
    }

}
